// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// s [author] rhyme_lph
// N [email]  rhymelph@gmail.com
// A [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/coa_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/common/expandable.dart';
import 'package:finance_app/src/widgets/common/normal_table_pro.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/chart_account_item.dart';
import 'package:finance_app/src/widgets/list_item/list_expandable_item.dart';
import 'package:finance_app/src/widgets/list_item/time_select_item.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/setting/chart_of_accounts_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';

@RouterMeta(paramName: "chartOfAccountsPage")
class ChartOfAccountsPage extends StatefulWidget {
  final bool isSelectMode;
  final int editId;

  const ChartOfAccountsPage({Key key, this.isSelectMode, this.editId})
      : super(key: key);

  @override
  _ChartOfAccountsPageState createState() => _ChartOfAccountsPageState();
}

class _ChartOfAccountsPageState extends State<ChartOfAccountsPage>
    with PagePresenter<ChartOfAccountsPage, ChartOfAccountsProvider> {
  List<ExpandableController> expandControllerList = [
    ExpandableController(initialExpanded: true),
    ExpandableController(initialExpanded: false),
  ];

  @override
  void initState() {
    provider.isSelectMode = widget.isSelectMode;
    provider.editId = widget.editId;
    provider.searchController.addListener(() {
      if (provider.searchController.text.isNotEmpty) {
        for (ExpandableController controller in expandControllerList) {
          controller.expanded = true;
        }
      }
      provider.update();
    });
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.chart_of_accounts, actions: [
        if (widget.isSelectMode != true)
          NormalMorePopupButton(
            menuList: provider.menuList,
            onSelect: provider.onSelectMenu,
          )
      ]);

  @override
  Widget get buildWidget => Stack(
        children: [
          _buildAccountList(),
          if (widget.isSelectMode != true) _buildBottomButton(),
        ],
      );

  Widget _buildAccountList() => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            listBuilder<DateTime>(
              selector: (_, __) => __.asAt,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  TimeSelectItem(
                      title: S.current.as_at,
                      value: value == null
                          ? Config.settingInfo.dateFormat.toUpperCase() ??
                              "DD MMM YYYY"
                          : DateTimeUtils.formatGlobalDateTime(value),
                      onTap: provider.onSelectAsAt),
            ),
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.h20,
            Expanded(
              child: ListView(
                controller: provider.controller,
                children: [
                  NormalTableProHeader(
                    items: [
                      S.current.account,
                      '${S.current.balance} (${Config.defaultCurrency.key})',
                    ],
                  ),
                  listBuilder<List<CoaByGroupEntity>>(
                    selector: (_, __) => List.from(__.data),
                    builder: (BuildContext context,
                        List<CoaByGroupEntity> value, Widget child) {
                      List<Widget> children = [];
                      for (final item in value) {
                        final data = item.coaAccountDetail
                            .where((element) =>
                                RegExpUtils.getSearchRegExp(
                                        provider.searchController.text)
                                    .hasMatch(element.name) ||
                                RegExpUtils.getSearchRegExp(
                                        provider.searchController.text)
                                    .hasMatch(element.accountCode))
                            .toList();

                        if (data.length > 0) {
                          children.add(ListExpandableItem(
                            controller: expandControllerList[
                                provider.data.indexOf(item)],
                            title: item.groupName,
                            content: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: data
                                  .map((e) => ChartAccountItem(
                                        title: e.externalAccountCode,
                                        status: e.crdrNature == "DR"
                                            ? S.current.debit
                                            : S.current.credit,
                                        name: e.name,
                                        isChild: e.parentAccountId != 0,
                                        // amount:
                                        //     '${e.currencyCode} ${CashUtils.formatCashAmount(e.balance)}',
                                        amount:
                                            '${CashUtils.formatCashAmount(e.balance)}',
                                        onTap: () => provider
                                            .onNavAccountDetail(e, data),
                                      ))
                                  .toList(),
                            ),
                          ));
                        }
                      }
                      children.addAll([
                        AppSpaces.h25,
                        _buildTotalWidget(),
                      ]);
                      children.add(AppSpaces.h90);
                      return Column(
                        children: children,
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      );

  Widget _buildBottomButton() => listBuilder<bool>(
        selector: (_, __) => __.buttonBarIsUp,
        builder: (BuildContext context, bool value, Widget child) =>
            AnimatedPositioned(
                duration: Duration(milliseconds: 300),
                left: 0.0,
                right: 0.0,
                bottom: value
                    ? MediaQuery.of(context).padding.bottom + getDp(40)
                    : -getDp(60),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    NormalFloatSvgButton(
                      onTap: provider.onNavAdd,
                      asset: A.assetsImagesDashboardAdd,
                    ),
                  ],
                )),
      );

  Widget _buildTotalWidget() => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          DefaultTextStyle(
            style: TextStyle(
              color: aceDarkGrayColor,
              fontSize: getSp(16),
              fontWeight: FontWeight.w400,
              height: 22 / 14,
              fontFamily: "DinRoundPro",
            ),
            child: Column(
              children: [
                Text(S.current.total_debit),
                AppSpaces.h15,
                Text(S.current.total_credit),
                AppSpaces.h15,
                Text(S.current.difference),
              ],
            ),
          ),
          AppSpaces.w10,
          DefaultTextStyle(
            style: TextStyle(
              color: aceDarkGrayColor,
              fontSize: getSp(16),
              fontWeight: FontWeight.w700,
              height: 22 / 14,
              fontFamily: "DinRoundPro",
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                listBuilder<String>(
                  selector: (_, __) =>
                      CashUtils.formatCashAmount(__.debitTotal),
                  builder: (BuildContext context, String value, Widget child) =>
                      Text('SGD $value'),
                ),
                AppSpaces.h15,
                listBuilder<String>(
                  selector: (_, __) =>
                      CashUtils.formatCashAmount(__.creditTotal),
                  builder: (BuildContext context, String value, Widget child) =>
                      Text('SGD $value'),
                ),
                AppSpaces.h15,
                listBuilder<String>(
                  selector: (_, __) =>
                      CashUtils.formatCashAmount(__.difference),
                  builder: (BuildContext context, String value, Widget child) =>
                      Text('SGD $value'),
                ),
              ],
            ),
          ),
          AppSpaces.w35,
        ],
      );
}
